<?php
/**
 * Created by PhpStorm.
 * User: Chris
 * Date: 14-5-1
 * Time: 下午10:07
 */

use Auth\Auth;

class Controller_Admin_Login extends Controller_Template
{

    public function action_logout(){
        Auth::instance('Simpleauth')->logout();
//        $this->template->content = View::forge('admin/login/index');
//        Response::redirect("admin/login");
        Response::redirect("/");
    }

    private function checkVerifyCode($data){
        $verifycode = Session::get(SESSION_ADMIN_LOGIN_VERIFY_CODE);
        $verifycodeInput = Input::param('verifycode', '');
        if ($verifycodeInput==''){
            Session::set_flash('error', '验证码错误');
            $data['login_error'] = '验证码错误';
            return false;
        }else{
            if ( $verifycode!=$verifycodeInput ){
                Session::set_flash('error', '验证码错误');
                $data['login_error'] = '验证码错误';
                return false;
            }
        }
        return true;
    }

    public function action_index()
    {
        $auth = Auth::instance('Simpleauth');
        if ($auth->check()){
            Response::redirect("admin/user");
            return;
        }

        $data = array();
        if (Input::method() == 'POST') {
            $name = Input::param('username');
            $pass = Input::param('password');


            if ($this->checkVerifyCode($data)){
                if ($user = $auth->login($name, $pass))
                {
                    // the combination of $name and $pass validated, print the users screen name
//                echo $user['username'];
                    Response::redirect('admin/user');
                }else{
                    Session::set_flash('error', '帐号或密码错误');

//                Auth::create_user('Chris','qwe123','anewuser@example.org',1,array('fullname' => 'Chris Hu',));
                    $data['username']    = $name;
                    $data['login_error'] = '帐号或密码错误';

                }
            }
        }

        $data= array();
        $this->template->title = '后台管理';
        $this->template->content = View::forge('admin/login', $data);
    }

}